package com.atm.interceptor;


import com.atm.annotation.NeedLogin;
import com.atm.config.Const;
import com.atm.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// api拦截器
@Slf4j
@Component
public class AppApiInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod))
            return super.preHandle(request, response, handler);

        NeedLogin annotation = ((HandlerMethod) handler).getMethod().getAnnotation(NeedLogin.class);
        if (annotation != null) {
            String token = getToken(request);
            if (StringUtils.isEmpty(token)) {
                log.error("未携带token，拦截，请求路径[{}][{}]", request.getMethod(), request.getServletPath());
                response.setHeader("content-type", "application/json;charset=UTF-8 ");
                response.getWriter().println("{\"code\":10001,\"message\":\"未携带token\",\"data\":null}");
                response.flushBuffer();
                return false;
            }

            // 检测token的有效性
            if (!JWTUtil.verify(token)){
                response.setHeader("content-type", "application/json;charset=UTF-8 ");
                response.getWriter().println("{\"code\":10001,\"message\":\"token无效\",\"data\":null}");
                response.flushBuffer();
                return false;
            }

            // 将wxOpenid放到request的属性里
            request.setAttribute(Const.AccountNo, JWTUtil.getAccountIdFromToken(token));
        }

        return super.preHandle(request, response, handler);
    }

    // 找请求里携带的token
    public static String getToken(HttpServletRequest request) {
        final String tokenParam = Const.Token;
        String token = request.getParameter(tokenParam); // 从url后面的参数里找
        if (StringUtils.isEmpty(token)) // 从header里面找
            token = request.getHeader(tokenParam);
        return token;
    }
}



